package cn.com.wdjedu.androidapp.wjeduandroid.ui.mainfragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.mrjian.banner.CBViewHolderCreator;
import com.mrjian.banner.ConvenientBanner;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.com.wdjedu.androidapp.wjeduandroid.R;
import cn.com.wdjedu.androidapp.wjeduandroid.mvp.MvpFragment;
import cn.com.wdjedu.androidapp.wjeduandroid.mvp.main.MainPresenter;
import cn.com.wdjedu.androidapp.wjeduandroid.mvp.main.Mainview;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.Constanct;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.utils.NetworkImageHolderView;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.MyGifView;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.MyGridView;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.MyListView;
import cn.com.wdjedu.androidapp.wjeduandroid.ui.introduceui.CourseIntroduceActivity;

/**
 * 首页界面
 */

public class MainFragment extends MvpFragment<MainPresenter> implements Mainview {

    @BindView(R.id.adc_banner)
    ConvenientBanner mAdcBanner;
    @BindView(R.id.gridview)
    MyGridView mGridview;
    @BindView(R.id.listview)
    MyListView mListview;
    @BindView(R.id.sheep_gif_home)
    MyGifView sheepGifHome;
    @BindView(R.id.textViewLoading_home)
    TextView textViewLoadingHome;
    @BindView(R.id.progressBar_home)
    ProgressBar progressBarHome;
    @BindView(R.id.home_container)
    ScrollView homeContainer;
    private View view;
    //类型列表数据
    private List<MainBean.TypesBean> types;
    private ClassflyItemAdapter mClassflyItemAdapter;
    //视频列表数据
    private List<MainBean.CourseBean> videos;
    private VideoItemAdapter mVideoItemAdapter;
    private static final String FRAGMENT_MAIN = "fragment_main";
    /**
     * 标志位，标志已经初始化完成
     */
    private boolean isPrepared;
    private List<String> networkImages;

    //计时器
    private CountDownTimer timer;
    //第一次打开自动刷新一次
    private boolean open_firstime = true;


    public static MainFragment newInstance(int index) {
        Bundle bundle = new Bundle();
        bundle.putInt(FRAGMENT_MAIN, index);
        MainFragment fragment = new MainFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mvpPresenter != null) {
            mvpPresenter.attach(this);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        if (!isNetWorkConnected(getActivity().getApplication())) {
            Toast.makeText(getActivity().getApplication(), "没有网络,请检查您的手机是否联网", Toast.LENGTH_LONG).show();
        }
        //页面切换时也当做第一次打开
        open_firstime = true;

        if (view == null) {
            view = inflater.inflate(R.layout.fragment_main, null);
            ButterKnife.bind(this, view);
            //获得索引值
            Bundle bundle = getArguments();
            if (bundle != null) {
                int mCurIndex = bundle.getInt(FRAGMENT_MAIN);
            }
            isPrepared = true;
            lazyLoad();
        }

        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        ButterKnife.bind(this, view);
        initData();
        Map<String, String> maps = new HashMap<>();
        mvpPresenter.queryMainData(maps);

        return view;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        types = new ArrayList<>();
        videos = new ArrayList<>();
        mClassflyItemAdapter = new ClassflyItemAdapter(getActivity().getApplication(), types);
        mGridview.setAdapter(mClassflyItemAdapter);
        mVideoItemAdapter = new VideoItemAdapter(getActivity().getApplication(), R.layout.item_main_listview, videos);
        mListview.setAdapter(mVideoItemAdapter);
        mGridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0 || position == 1 || position == 2 || position == 3) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("CourseType", position + 1);
                    switch (position) {
                        case 0:
                            bundle.putString("CourseName", "UI");
                            break;
                        case 1:
                            bundle.putString("CourseName", "Java");
                            break;
                        case 2:
                            bundle.putString("CourseName", "Swift");
                            break;
                        case 3:
                            bundle.putString("CourseName", "Android");
                            break;
                        default:
                            break;
                    }
                    Intent intent = new Intent(getActivity().getApplication(), CourseIntroduceActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), "课程正在骑马来的路上~~", Toast.LENGTH_SHORT).show();
                }

            }
        });

        //无网络或数据时，允许用户刷新页面
        if (!isNetWorkConnected(getActivity().getApplication()) || mListview.getCount() == 0 || mGridview.getCount() == 0) {
            showProgress(true);
        } else {
            showProgress(false);
        }


        //重新加载
        View.OnClickListener refresh = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBarHome.setVisibility(View.VISIBLE);
                textViewLoadingHome.setText("玩命加载中~~");
                sheepGifHome.setEnabled(false);//防止用户加载时多次点击
                textViewLoadingHome.setEnabled(false);//防止用户加载时多次点击
                onResume();
                initData();
                Map<String, String> maps = new HashMap<>();
                mvpPresenter.queryMainData(maps);

                timer = new CountDownTimer(10000, 1000) {
                    public void onTick(long millisUntilFinished) {
                        if (mListview.getCount() != 0 && mGridview.getCount() != 0) {
                            progressBarHome.setVisibility(View.GONE);
                            showProgress(false);
                            timer.cancel();
                        }
                    }

                    public void onFinish() {
                        Toast.makeText(getActivity().getApplicationContext(), "加载超时,请检查网络", Toast.LENGTH_SHORT).show();
                        textViewLoadingHome.setText("客官网络不太好，点击刷新");
                        progressBarHome.setVisibility(View.GONE);
                        sheepGifHome.setEnabled(true);//允许用户再次加载
                        textViewLoadingHome.setEnabled(true);//允许用户再次加载
                        timer.cancel();
                    }
                };
                timer.start();
            }
        };
        textViewLoadingHome.setOnClickListener(refresh);
        sheepGifHome.setOnClickListener(refresh);


        final Runnable updateThread_Refresh = new Runnable() {
            @Override
            public void run() {
                try {
                    //更新UI
                    textViewLoadingHome.performClick();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        if (open_firstime) {
            //Toast.makeText(getActivity().getApplicationContext(), "第一次打开", Toast.LENGTH_SHORT).show();
            new Thread() {
                @Override
                public void run() {
                    //这里写入子线程需要做的工作
                    try {
                        Thread.sleep(1000);
                        getActivity().runOnUiThread(updateThread_Refresh);
                        open_firstime = false;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            homeContainer.setAlpha(show ? (float) 0.3 : (float) 1);
            homeContainer.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    //loginForm.setVisibility(show ? View.GONE : View.VISIBLE);
                    homeContainer.setAlpha(show ? (float) 0.3 : (float) 1);
                }
            });
            sheepGifHome.setVisibility(show ? View.VISIBLE : View.GONE);
            sheepGifHome.setMovieResource(R.raw.sheep);
            textViewLoadingHome.setVisibility(show ? View.VISIBLE : View.GONE);
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            homeContainer.setAlpha(show ? (float) 0.3 : (float) 1);
            sheepGifHome.setVisibility(show ? View.VISIBLE : View.GONE);
            textViewLoadingHome.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    protected void lazyLoad() {
        //无网络或无数据时，允许用户刷新页面

        if (!isPrepared || !isVisible) {
            return;
        }


    }

    @Override
    protected void onInvisible() {
        //初始化界面
        if (view != null) {

        }
        super.onInvisible();
    }


    @Override
    public void showLoading() {
//        mProgressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
//        mProgressBar.setVisibility(View.GONE);
    }

    @Override
    public void showError(String error) {
        Logger.d(error);
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }

    /**
     * 查詢成功首頁的數據
     *
     * @param mainBean
     */
    @Override
    public void queryNewMainData(MainBean mainBean) {
        //设置显示的指示器的图
        networkImages = new ArrayList<>();
        if (mainBean.getAds() != null && mainBean.getAds() != null) {
            for (int j = 0; j < mainBean.getAds().size(); j++) {
                networkImages.add(Constanct.IMAGE_URL + mainBean.getAds().get(j).getImage());
            }
        }
        mAdcBanner.setPageIndicator(new int[]{R.mipmap.icon_point, R.mipmap.icon_point_pre})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
//                    .startTurning(2000)
                //设置翻页的效果，不需要翻页效果可用不设
                .setPageTransformer(ConvenientBanner.Transformer.DefaultTransformer);

        //设置翻页的适配器
        mAdcBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImages);
        if (networkImages.size() > 1) {
            mAdcBanner.startTurning(2000);
        }
        //刷新类别数据
        mClassflyItemAdapter.updateAddAll(mainBean.getTypes());
        //刷新视频数据
        videos.clear();
        videos.addAll(mainBean.getCourse());
        mVideoItemAdapter.notifyDataSetChanged();

    }

    private boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}
